using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace QQZiFramework
{

    public class ApiJsonMessage
    {
        public ApiJsonMessage(DBContext context)
        {
            this.context = context;
        }
        public const string Success_Code = "success";
        public const string Err_Code = "err";
        /// <summary>
        /// 成功success,失败err
        /// </summary>
        public string code { get; set; }

        public object result { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string message { get; set; }

        

        public void PostAsync(string url, object result, bool success, string error, string appId, string secret)
        {
            if (success)
            {
                this.code = Success_Code;
                this.message = "成功";
            }
            else
            {
                this.message = error;
                this.code = Err_Code;
            }
            this.appId = appId;
            this.secret = secret;
            System.Collections.Generic.Dictionary<string, string> nvc = new System.Collections.Generic.Dictionary<string, string>();
            nvc.Add("code", this.code);
            nvc.Add("message", this.message);
            nvc.Add("appId", appId);
            foreach (System.Reflection.PropertyInfo propertyInfo in result.GetType().GetProperties())
            {
                object val = propertyInfo.GetValue(result);
                string value = "";
                if (val != null)
                {
                    if (val.GetType().Name.ToLower() == "decimal") { value = ((decimal)val).ToString("f2"); }
                    else value = val.ToString();
                }
                nvc.Add(propertyInfo.Name, value);
            }
            nvc.Add("timespan", Utility.GetIntFromTime(DateTime.Now).ToString());
            string signMsg = GetEncryptMd5(nvc);
            nvc.Add("sign", signMsg); 
            MyHttpUtility http = context.NewHttpUtility();
            string str = http.DoPost(url,postData);
            if (str == null || str.Length > 10 || str.ToLower() != "success")
            {
                context.LogMessage(str, "商户回调");
                throw new Exception("客户已接收回调，但返回内容不是success");
            }
        }



        public void SetSuccess(object result, string appId, string secret)
        {
            this.code = Success_Code;
            this.appId = appId;
            this.secret = secret;
            System.Collections.Generic.Dictionary<string, string> nvc = new System.Collections.Generic.Dictionary<string, string>();
            nvc.Add("appId", appId);
            foreach (System.Reflection.PropertyInfo propertyInfo in result.GetType().GetProperties())
            {
                object val = propertyInfo.GetValue(result);
                string value = "";
                if (val != null)
                {
                    if (val.GetType().Name.ToLower() == "decimal") { value = ((decimal)val).ToString("f2"); }
                    else value = val.ToString();
                }
                nvc.Add(propertyInfo.Name, value);
            }
            nvc.Add("timespan", Utility.GetIntFromTime(DateTime.Now).ToString());
            string signMsg = GetEncryptMd5(nvc);
            nvc.Add("sign", signMsg);
            this.result = nvc;
            this.message = "成功";
        }

        public void SetErr(string err)
        {
            message = err;
            code = Err_Code;
        }

        DBContext context;
        string appId, secret;

        string postData;



        public string GetEncryptMd5(Dictionary<string, string> nvc)
        {
            postData = ToParamString(nvc);
            string strEncrypt = postData + secret;
            string compare = Utility.EncryptMD5(strEncrypt).ToUpper();
            this.context.LogMessage("MD5明文:" + strEncrypt + "   MD5密文:" + compare, "授权登录");
            postData += "&sign=" + compare;
            return compare;

        }

        private string ToParamString(Dictionary<string, string> nvc)
        {
            string strEncrypt = "";
            foreach (string key in nvc.Keys)
            {
                strEncrypt += "&" + key + "=" + System.Net.WebUtility.UrlEncode(nvc[key]);
            }
            if (strEncrypt.Length > 0) strEncrypt = strEncrypt.Substring(1);
            return strEncrypt;
        }

        bool ignoreDefaultValue = true;

        public JsonSerializerSettings GetSerializerSettings()
        {
            var jSetting = new JsonSerializerSettings { };
            if (ignoreDefaultValue)
            {
                jSetting.DefaultValueHandling = DefaultValueHandling.Ignore;
                jSetting.NullValueHandling = NullValueHandling.Ignore;
            }
            jSetting.Formatting = Formatting.Indented;
            jSetting.MaxDepth = 10; //设置序列化的最大层数  
            return jSetting;
        }

        public string ToJson()
        {

            string str = JsonConvert.SerializeObject(this, GetSerializerSettings());
            str = str.Replace("-999999.0", "null").Replace("-999999", "null");
            return str;
        }
    }

    public class ApiJsonMessage<T>
    {
        public string code { get; set; }

        public T result { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string message { get; set; }

    }
}